package cn.darkhorse.device.service.impl;

import cn.darkhorse.common.config.DbTypeConfig;
import cn.darkhorse.common.constant.CommonConstant;
import cn.darkhorse.device.dao.IotGatewayDao;
import cn.darkhorse.device.dto.IotGatewayDTO;
import cn.darkhorse.device.iot.constant.IotConstant;
import cn.darkhorse.device.mapper.AlarmParameterSettingsMapper;
import cn.darkhorse.device.pojo.*;
import cn.darkhorse.device.mapper.IotGatewayMapper;
import cn.darkhorse.device.service.IotGatewayService;
import cn.darkhorse.device.service.IotPointTableService;
import cn.darkhorse.device.service.MesDeviceService;
import cn.darkhorse.device.service.MesThirdPartyDataService;
import cn.darkhorse.device.vo.IotGatewayVO;
import cn.darkhorse.device.vo.IotPointTableVO;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuanjun
 * @since 2023-10-11
 */
@Service
public class IotGatewayServiceImpl extends JoinServiceImpl<IotGatewayMapper, IotGateway> implements IotGatewayService {

    @Resource
    private IotPointTableService iotPointTableService;
    @Resource
    private MesDeviceService mesDeviceService;
    @Resource
    private AlarmParameterSettingsMapper alarmParameterSettingsMapper;
    @Resource
    private RedisCache redisCache;
    @Resource
    private MesThirdPartyDataService mesThirdPartyDataService;
    @Resource
    private DbTypeConfig dbTypeConfig;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //前缀
    public static String PRE="history_";

    /**
     * 列表
     *
     * @param dto
     * @return
     */
    @Override
    public TableDataInfo listAll(IotGatewayDTO dto) {
        LambdaQueryWrapper<IotGateway> wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByDesc(IotGateway::getId);
        JoinLambdaWrapper<IotGateway> joinLambdaWrapper = new JoinLambdaWrapper<>(IotGateway.class);
        if(StringUtils.isNotBlank(dto.getGatewayDeviceId())){
            wrapper.like(IotGateway::getGatewayDeviceId,dto.getGatewayDeviceId());
            joinLambdaWrapper.like(IotGateway::getGatewayDeviceId,dto.getGatewayDeviceId());
        }
        if(null!=dto.getIsCreateTable()){
            wrapper.eq(IotGateway::getIsCreateTable, dto.getIsCreateTable());
            joinLambdaWrapper.eq(IotGateway::getIsCreateTable, dto.getIsCreateTable());
        }
//        if(null!=dto.getDeviceType()){
//            wrapper.eq(IotGateway::getDeviceType,dto.getDeviceType());
//            joinLambdaWrapper.eq(IotGateway::getDeviceType,dto.getDeviceType());
//        }
        List<IotGateway> list =new ArrayList<>();
        if(StringUtils.isNotBlank(dto.getDeviceName())){
            joinLambdaWrapper.leftJoin(MesDevice.class, MesDevice::getId, IotGateway::getDeviceId)
            .like(MesDevice::getName, dto.getDeviceName()).end();
            list = joinList(joinLambdaWrapper,IotGateway.class);
        }else{
            list=list(wrapper);
        }
        List<MesDevice> deviceList = mesDeviceService.list();
        Map<Long, String> collect = deviceList.stream().collect(Collectors.toMap(MesDevice::getId, MesDevice::getName));
        List<MesThirdPartyData> thirdList = mesThirdPartyDataService.list();
        Map<Long, String> thirdMap = thirdList.stream().collect(Collectors.toMap(MesThirdPartyData::getId, MesThirdPartyData::getName));
        List<IotGatewayVO> voList=new ArrayList<>();
        list.forEach(item->{
            IotGatewayVO vo=new IotGatewayVO();
            BeanUtils.copyProperties(item,vo);
            if(vo.getDeviceType()==0) {
                if (collect.containsKey(vo.getDeviceId())) {
                    vo.setDeviceName(collect.get(vo.getDeviceId()));
                }
            }
            if(vo.getDeviceType()==2) {
                if (thirdMap.containsKey(vo.getDeviceId())) {
                    vo.setDeviceName(thirdMap.get(vo.getDeviceId()));
                }
            }
            voList.add(vo);
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(voList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 查看
     *
     * @param iotId
     * @return
     */
    @Override
    public IotGatewayVO view(Long iotId) {
        IotGatewayVO vo=new IotGatewayVO();
        IotGateway byId = getById(iotId);
        if(null!=byId){
            List<IotPointTableVO> voList=new ArrayList<>();
            if(byId.getDeviceType()==0){
                MesDevice device = mesDeviceService.getById(byId.getDeviceId());
                BeanUtils.copyProperties(byId,vo);
                LambdaQueryWrapper<IotPointTable> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(IotPointTable::getGatewayDeviceId,byId.getGatewayDeviceId());
                List<IotPointTable> list = iotPointTableService.list(wrapper);
                list.forEach(item->{
                    IotPointTableVO voItem=new IotPointTableVO();
                    BeanUtils.copyProperties(item,voItem);
                    voItem.setDeviceName(device.getName());
                    voList.add(voItem);
                });
                vo.setDeviceName(device.getName());
            }

            if(byId.getDeviceType()==2){
                MesThirdPartyData third = mesThirdPartyDataService.getById(byId.getDeviceId());
                BeanUtils.copyProperties(byId,vo);
                LambdaQueryWrapper<IotPointTable> wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(IotPointTable::getGatewayDeviceId,byId.getGatewayDeviceId());
                List<IotPointTable> list = iotPointTableService.list(wrapper);
                list.forEach(item->{
                    IotPointTableVO voItem=new IotPointTableVO();
                    BeanUtils.copyProperties(item,voItem);
                    voItem.setDeviceName(third.getName());
                    voList.add(voItem);
                });
                vo.setDeviceName(third.getName());
            }
            vo.setTableList(voList);
        }
        return vo;
    }

    /**
     * 保存
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveIot(IotGatewayVO vo) {
        Long iotId=-1L;
        LambdaQueryWrapper<IotGateway> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(IotGateway::getGatewayDeviceId,vo.getGatewayDeviceId());
        if(null!=vo.getId()){
            wrapper.ne(IotGateway::getId,vo.getId());
        }
        Long count=count(wrapper);
        if(count>0){
            throw new ServiceException("已存在该设备ID点表！");
        }
        IotGateway gateway=new IotGateway();
        BeanUtils.copyProperties(vo,gateway);
        if(null==vo.getId()){
            gateway.setIsCreateTable(false);
        }
        gateway.setHistoryTableName(PRE+gateway.getGatewayDeviceId());
        saveOrUpdate(gateway);
        //更新主表
        //设备
        if(vo.getDeviceType()==0) {
            MesDevice byId = mesDeviceService.getById(gateway.getDeviceId());
            if (null != byId) {
                byId.setGatewayDeviceId(vo.getGatewayDeviceId());
                byId.setHistoryTableName(PRE + vo.getGatewayDeviceId());
                mesDeviceService.updateById(byId);
            }
        }
        //电表
//        if(vo.getDeviceType()==1) {
//            MesMeter byId = mesMeterService.getById(gateway.getDeviceId());
//            if (null != byId) {
//                byId.setGatewayDeviceId(vo.getGatewayDeviceId());
//                byId.setHistoryTableName(PRE + vo.getGatewayDeviceId());
//                byId.setMeterHistoryTableName(PRE + vo.getGatewayDeviceId());
//                mesMeterService.updateById(byId);
//            }
//        }
        //三方
        if(vo.getDeviceType()==2) {
            MesThirdPartyData byId = mesThirdPartyDataService.getById(gateway.getDeviceId());
            if (null != byId) {
                byId.setGatewayDeviceId(vo.getGatewayDeviceId());
                byId.setHistoryTableName(PRE + vo.getGatewayDeviceId());
                mesThirdPartyDataService.updateById(byId);
            }
        }
        //删除旧数据
        LambdaQueryWrapper<IotPointTable> tableWrapper=new LambdaQueryWrapper<>();
        tableWrapper.eq(IotPointTable::getGatewayDeviceId,gateway.getGatewayDeviceId());
        List<IotPointTable> list = iotPointTableService.list(tableWrapper);
        Set<String> pointSet= list.stream().map(IotPointTable::getPointId).collect(Collectors.toSet());
        ;
        //iotPointTableService.remove(tableWrapper);
        // 根据指定属性分组，并统计数量（key：指定属性，value：数量）
        Map<Object, Long> fieldMap = vo.getTableList().stream().collect(Collectors.groupingBy(item -> item.getFieldName(), Collectors.counting()));
        Stream<Object> fieldStream = fieldMap.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey());
        Map<Object, Long> pointMap = vo.getTableList().stream().collect(Collectors.groupingBy(item -> item.getPointId(), Collectors.counting()));
        Stream<Object> pointStream = pointMap.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey());
        Map<Object, Long> pNameMap = vo.getTableList().stream().collect(Collectors.groupingBy(item -> item.getPointName(), Collectors.counting()));
        Stream<Object> pNameStream = pNameMap.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey());
        pointStream.forEach(item->{
            throw new ServiceException("存在重复变量标识"+item);
        });
        fieldStream.forEach(item->{
            throw new ServiceException("存在重复属性标识"+item);
        });
        pNameStream.forEach(item->{
            throw new ServiceException("存在重复属性名"+item);
        });
        //更新子表
        vo.getTableList().forEach(item->{
            if(StringUtils.isBlank(item.getFieldName())){
                item.setFieldName(item.getPointId());
            }
            if(!validateValue(item.getExtraJson(),item.getDataType())){
                throw new ServiceException("属性【"+item.getPointName()+"】存在重复标识值，不允许提交！");
            }
            item.setGatewayDeviceId(gateway.getGatewayDeviceId());
            item.setDeviceId(gateway.getDeviceId());
            tableWrapper.clear();
            tableWrapper.eq(IotPointTable::getPointId,item.getPointId());
            tableWrapper.eq(IotPointTable::getDeviceId,item.getDeviceId());
            IotPointTable one = iotPointTableService.getOne(tableWrapper);
            if(null!=one){
                one.setPointName(item.getPointName());
                one.setDescription(item.getDescription());
                one.setGatewayDeviceId(item.getGatewayDeviceId());
                one.setExtraJson(item.getExtraJson());
                one.setGatewayDeviceId(vo.getGatewayDeviceId());
                one.setInputType(item.getInputType());
                one.setDataFormula(item.getDataFormula());
                one.setDataType(item.getDataType());
                one.setScale(item.getScale());
                iotPointTableService.updateById(one);
            }else{
                iotPointTableService.save(item);
            }
            if(pointSet.contains(item.getPointId())){
                pointSet.remove(item.getPointId());
            }
        });
        if(null!=pointSet&&pointSet.size()>0){
            tableWrapper.clear();
            tableWrapper.in(IotPointTable::getPointId,pointSet);
            tableWrapper.eq(IotPointTable::getGatewayDeviceId,vo.getGatewayDeviceId());
            iotPointTableService.remove(tableWrapper);
        }
        iotId=gateway.getId();
        return iotId;
    }

    /**
     * 校验值是否重复
     * @param extraJson
     * @param type
     * @return
     */
    public boolean validateValue(String extraJson,Integer type){
        //0：布尔型1：数值型2：字符型3：枚举型4：二进制
        if(type!=0&&type!=3){
            return true;
        }
        JSONArray jsonArray = JSONArray.parseArray(extraJson);
        Set<String> labelSet=new HashSet<>();
        if(!jsonArray.isEmpty()){
            for (Object o : jsonArray) {
                JSONObject obj=JSONObject.parseObject(o.toString());
                String label=obj.containsKey("label")?obj.get("label").toString():"";
                if(labelSet.contains(label)){
                    return false;
                }else{
                    labelSet.add(label);
                }
            }
        }
        return true;
    }

    /**
     * 删除
     *
     * @param iotId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long iotId) {
        IotGateway byId = getById(iotId);
        if(byId.getDeviceType()==0){
            LambdaQueryWrapper<MesDevice> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(MesDevice::getGatewayDeviceId,byId.getGatewayDeviceId());
            MesDevice one = mesDeviceService.getOne(wrapper);
            if(null!=one){
                //删除报警记录
                String alarmRecordSql="delete from alarm_record_info where device_id="+byId.getDeviceId();
                SqlRunner.db().delete(alarmRecordSql);
                //删除历史表
                String sql="IF EXISTS ( SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID( N'[dbo].["+byId.getHistoryTableName()+"]' ) AND type IN ( 'U' ) ) DROP TABLE [dbo].["+byId.getHistoryTableName()+"]";
                if (dbTypeConfig.getType().equals(CommonConstant.DB_TYPE_MYSQL)) {
                    sql="drop table if exists`"+byId.getHistoryTableName()+"`";
                }
                SqlRunner.db().delete(sql);
                //设备表置空
                LambdaUpdateWrapper<MesDevice> deviceLambdaUpdateWrapper = Wrappers.lambdaUpdate();
                deviceLambdaUpdateWrapper.eq(MesDevice::getId, byId.getDeviceId());
                deviceLambdaUpdateWrapper.set(MesDevice::getGatewayDeviceId, null);
                deviceLambdaUpdateWrapper.set(MesDevice::getHistoryTableName, null);
                mesDeviceService.update(deviceLambdaUpdateWrapper);
            }
        }
//        if(byId.getDeviceType()==1){
//            LambdaQueryWrapper<MesMeter> wrapper=new LambdaQueryWrapper<>();
//            wrapper.eq(MesMeter::getGatewayDeviceId,byId.getGatewayDeviceId());
//            MesMeter one = mesMeterService.getOne(wrapper);
//            if(null!=one){
//                /*//删除报警记录
//                String alarmRecordSql="delete from alarm_record_info where device_id="+byId.getDeviceId();
//                SqlRunner.db().delete(alarmRecordSql);
//                //删除历史表
//                String sql="IF EXISTS ( SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID( N'[dbo].["+byId.getHistoryTableName()+"]' ) AND type IN ( 'U' ) ) DROP TABLE [dbo].["+byId.getHistoryTableName()+"]";
//                SqlRunner.db().delete(sql);*/
//                //设备表置空
//                LambdaUpdateWrapper<MesMeter> deviceLambdaUpdateWrapper = Wrappers.lambdaUpdate();
//                deviceLambdaUpdateWrapper.eq(MesMeter::getId, byId.getDeviceId());
//                deviceLambdaUpdateWrapper.set(MesMeter::getGatewayDeviceId, null);
//                deviceLambdaUpdateWrapper.set(MesMeter::getMeterHistoryTableName,null);
//                deviceLambdaUpdateWrapper.set(MesMeter::getHistoryTableName, null);
//                mesMeterService.update(deviceLambdaUpdateWrapper);
//            }
//        }
        if(byId.getDeviceType()==2){
            LambdaQueryWrapper<MesThirdPartyData> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(MesThirdPartyData::getGatewayDeviceId,byId.getGatewayDeviceId());
            MesThirdPartyData one = mesThirdPartyDataService.getOne(wrapper);
            if(null!=one){
                /*//删除报警记录
                String alarmRecordSql="delete from alarm_record_info where device_id="+byId.getDeviceId();
                SqlRunner.db().delete(alarmRecordSql);
                //删除历史表
                String sql="IF EXISTS ( SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID( N'[dbo].["+byId.getHistoryTableName()+"]' ) AND type IN ( 'U' ) ) DROP TABLE [dbo].["+byId.getHistoryTableName()+"]";
                SqlRunner.db().delete(sql);*/
                //设备表置空
                LambdaUpdateWrapper<MesThirdPartyData> deviceLambdaUpdateWrapper = Wrappers.lambdaUpdate();
                deviceLambdaUpdateWrapper.eq(MesThirdPartyData::getId, byId.getDeviceId());
                deviceLambdaUpdateWrapper.set(MesThirdPartyData::getGatewayDeviceId, null);
                deviceLambdaUpdateWrapper.set(MesThirdPartyData::getHistoryTableName, null);
                mesThirdPartyDataService.update(deviceLambdaUpdateWrapper);
            }
        }
        //删除缓存
        redisCache.deleteObject(IotConstant.CACHE_MQTT_ALARM_PARAMS+byId.getGatewayDeviceId());
        redisCache.deleteObject(IotConstant.CACHE_MQTT_POINT_TABLE+byId.getGatewayDeviceId());
        //删除字段表
        LambdaQueryWrapper<IotPointTable> tableWrapper=new LambdaQueryWrapper<>();
        tableWrapper.eq(IotPointTable::getGatewayDeviceId,byId.getGatewayDeviceId());
        iotPointTableService.remove(tableWrapper);
        //删除参数表
        LambdaQueryWrapper<AlarmParameterSettings> settingWrapper=new LambdaQueryWrapper<AlarmParameterSettings>();
        settingWrapper.eq(AlarmParameterSettings::getGatewayDeviceId,byId.getGatewayDeviceId());
        alarmParameterSettingsMapper.delete(settingWrapper);
        boolean result = removeById(iotId);
        return result;
    }

    /**
     * 建表
     *
     * @param dataDeviceId
     * @return
     */
    @Override
    public boolean createTable(String dataDeviceId) {
        LambdaQueryWrapper<IotGateway> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(IotGateway::getGatewayDeviceId,dataDeviceId);
        IotGateway gateway = getOne(wrapper);
        if(null!=gateway){
            gateway.setIsCreateTable(true);
            String tableName=gateway.getHistoryTableName();
            LambdaQueryWrapper<IotPointTable> tableWrapper=new LambdaQueryWrapper<>();
            tableWrapper.eq(IotPointTable::getGatewayDeviceId,gateway.getGatewayDeviceId());
            List<IotPointTable> list = iotPointTableService.list(tableWrapper);



            String createSql="";
            if (dbTypeConfig.getType().equals(CommonConstant.DB_TYPE_SQLSERVER)) {
                createSql = "IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].[" + tableName + "]') AND type IN ('U'))\n" +
                        "\tDROP TABLE [dbo].[" + tableName + "]\n" +
                        "\n" +
                        "CREATE TABLE [dbo].[" + tableName + "] (\n" +
                        "  [id] bigint  IDENTITY(1,1) NOT NULL,\n" +
                        "  [created_at] datetime2(7)   NULL,\n" +
                        "  [flag] int  DEFAULT 0 NULL,\n" +
                        "  [gateway_device_id] nvarchar(max) COLLATE Chinese_PRC_CI_AS   NULL,\n";

                int index = 0;
                for (IotPointTable table : list) {
                    if ((index + 1) != list.size()) {
                        createSql += "[" + table.getFieldName() + "] nvarchar(max) COLLATE Chinese_PRC_CI_AS   NULL,\n";
                    } else {
                        createSql += "[" + table.getFieldName() + "] nvarchar(max) COLLATE Chinese_PRC_CI_AS   NULL \n";
                    }
                    index++;
                }
                createSql += ")\n";
                //创建索引
                createSql += "\n" +
                        "CREATE NONCLUSTERED INDEX [flag] ON [dbo].[" + tableName + "] ( [flag] ASC )\n";
                createSql += "\n" +
                        "ALTER TABLE [dbo].[" + tableName + "] SET (LOCK_ESCALATION = TABLE)\n";
                createSql += "\n" +
                        "EXEC sp_addextendedproperty\n" +
                        "'MS_Description', N'创建时间',\n" +
                        "'SCHEMA', N'dbo',\n" +
                        "'TABLE', N'" + tableName + "',\n" +
                        "'COLUMN', N'created_at'\n";
                createSql += "\n" +
                        "EXEC sp_addextendedproperty\n" +
                        "'MS_Description', N'硬件设备Id',\n" +
                        "'SCHEMA', N'dbo',\n" +
                        "'TABLE', N'" + tableName + "',\n" +
                        "'COLUMN', N'gateway_device_id'\n";
                createSql += "\n" +
                        "EXEC sp_addextendedproperty\n" +
                        "'MS_Description', N'处理标志',\n" +
                        "'SCHEMA', N'dbo',\n" +
                        "'TABLE', N'" + tableName + "',\n" +
                        "'COLUMN', N'flag'\n";
                //增加注释
                for (IotPointTable table : list) {
                    createSql += "\n" +
                            "EXEC sp_addextendedproperty\n" +
                            "'MS_Description', N'" + table.getPointName() + "',\n" +
                            "'SCHEMA', N'dbo',\n" +
                            "'TABLE', N'" + tableName + "',\n" +
                            "'COLUMN', N'" + table.getFieldName() + "'\n";
                }
            }
            if (dbTypeConfig.getType().equals(CommonConstant.DB_TYPE_MYSQL)) {
                createSql="drop table if exists `"+tableName+"`;\n";
                SqlRunner.db().update(createSql);
                createSql="CREATE TABLE "+tableName+"(\n" +
                        "  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',\n" +
                        "  `created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',\n" +
                        "  `flag` tinyint(4) DEFAULT '0' COMMENT '处理标志',\n" +
                        "  `gateway_device_id` varchar(100) DEFAULT NULL COMMENT '硬件设备Id',\n";
                for (IotPointTable table : list) {
                        createSql += "  `" + table.getFieldName() + "` varchar(255) DEFAULT NULL COMMENT '"+table.getPointName()+"',\n";
                }
                createSql+="  PRIMARY KEY (`id`)\n" +
                        ") ENGINE=InnoDB  COMMENT='"+tableName+"';";

            }
            System.out.println(createSql);
            boolean update = SqlRunner.db().update(createSql);
            updateById(gateway);
            return update;
        }
        return false;
    }

    /**
     * 是否建表
     *
     * @param gatewayDeviceId
     * @return
     */
    @Override
    public boolean hasTable(String gatewayDeviceId) {
        LambdaQueryWrapper<IotGateway> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(IotGateway::getGatewayDeviceId,gatewayDeviceId);
        IotGateway gateway = getOne(wrapper);
        if(null!=gateway){
            return gateway.getIsCreateTable();
        }
        return false;
    }

    /**
     * 字段名
     *
     * @param dto
     * @return
     */
    @Override
    public List<IotPointTable> export(IotGatewayDTO dto) {
        LambdaQueryWrapper<IotPointTable> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(IotPointTable::getGatewayDeviceId,dto.getGatewayDeviceId());
        List<IotPointTable> list = iotPointTableService.list(wrapper);
        return list;
    }

    /**
     * 删除表
     *
     * @param gatewayDeviceId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean dropTable(String gatewayDeviceId) {
        LambdaQueryWrapper<IotGateway> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(IotGateway::getGatewayDeviceId,gatewayDeviceId);
        IotGateway one = getOne(wrapper);
        if(null!=one){
            //删除缓存

            redisCache.deleteObject(IotConstant.CACHE_MQTT_ALARM_PARAMS+one.getGatewayDeviceId());
            redisCache.deleteObject(IotConstant.CACHE_MQTT_POINT_TABLE+one.getGatewayDeviceId());
            redisCache.deleteObject(IotConstant.CACHE_MQTT_DATA_REAL_DATA+one.getGatewayDeviceId());

            Boolean lastDevice = stringRedisTemplate.opsForHash().hasKey("last_device", one.getHistoryTableName());
            if (lastDevice){
                stringRedisTemplate.opsForHash().delete("last_device", one.getHistoryTableName());
            }
            //删除参数表
            LambdaQueryWrapper<AlarmParameterSettings> settingWrapper=new LambdaQueryWrapper<AlarmParameterSettings>();
            settingWrapper.eq(AlarmParameterSettings::getGatewayDeviceId,one.getGatewayDeviceId());
            alarmParameterSettingsMapper.delete(settingWrapper);
            //删除报警记录
            String alarmRecordSql="delete from alarm_record_info where device_id="+one.getDeviceId();
            SqlRunner.db().delete(alarmRecordSql);
            //删除历史表
            String sql="drop table "+one.getHistoryTableName();
            if (dbTypeConfig.getType().equals(CommonConstant.DB_TYPE_MYSQL)) {
                sql="drop table if exists`"+one.getHistoryTableName()+"`";
            }
            SqlRunner.db().delete(sql);
            one.setIsCreateTable(false);
            updateById(one);
            return true;
        }
        return false;
    }

    @Resource
    private IotGatewayDao iotGatewayDao;


    /**
     *
     * @param gatewayDeviceId
     * @param paramName
     * @return
     */
    @Override
    public List<IotPointTable> deviceParamsByGaDeId(String gatewayDeviceId, String paramName) {
        Map<String,Object> params = new HashMap<>();
        params.put("pointName",paramName);
        params.put("gatewayDeviceId",gatewayDeviceId);
        List<IotPointTable> pointTables = iotGatewayDao.pointTableList(params);
        return pointTables;
    }

    /**
     * 校验验证码
     *
     * @param code
     * @param uuid
     * @return
     */
    @Override
    public boolean validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new ServiceException("验证码错误！");
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new ServiceException("验证码错误！");
        }
        return true;
    }


}
